package com.itfreer.setting.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.PowerManager;
import android.provider.Settings;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import androidx.annotation.RequiresApi;

import com.itfreer.setting.R;
import com.itfreer.ui.activity.BaseActivity;
import com.itfreer.ui.base.TextView;
import com.xuexiang.keeplive.KeepLive;

/**
 * 权限设置
 */
public class PowerActivity extends BaseActivity {

    private LinearLayout power_content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting_power);

        // 返回
        TextView me =(TextView)findViewById(R.id.setting_power_back);
        me.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                finish();
            }
        });

        power_content =(LinearLayout)findViewById(R.id.power_content);

        loadPowerPage();
    }

    private void loadPowerPage() {
        // GPS权限设置
        Button gpsButton = (Button)findViewById(R.id.power_gps2);
        gpsButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivity(intent);
            }
        });

        // 电池优化
        Button powerButtonOne = (Button)findViewById(R.id.power_button_one);
        powerButtonOne.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // 点击电池优化设置
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // 忽略电池优化，支持Android6及以上
                    if(!isIgnoringBatteryOptimizations()) {
                        requestIgnoreBatteryOptimizations();
                    } else {
                        String str = "已优化完成，无需再次设置！";
                        showDialog(str);
                    }
                } else {
                    String str = "当前手机版本低于Android6.0，请自行优化！";
                    showDialog(str);
                }
            }
        });

        Button powerButtonTwo = (Button)findViewById(R.id.power_button_two);
        powerButtonTwo.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                // 点击后台运行权限
                KeepLive.gotoWhiteListActivity(PowerActivity.this, "轨迹服务");
            }
        });

        // 设置文本
        TextView optimization = findViewById(R.id.power_optimization);
        optimization.setText("由于系统的省电设置，可能会在巡护过程中误杀进程，请您将"+this.getString(R.string.app_name)+"加入电池保护名单中。");
        TextView backstage = findViewById(R.id.power_backstage);
        backstage.setText("为避免巡护路线异常、距离不准确、路线轨迹漂移等问题，建议您开启"+this.getString(R.string.app_name)+"的后台运行权限。");
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    private boolean isIgnoringBatteryOptimizations() {
        boolean isIgnoring = false;
        PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        if (powerManager != null) {
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(getPackageName());
        }
        return isIgnoring;
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    public void requestIgnoreBatteryOptimizations() {
        try {
            Intent intent = new Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivityForResult(intent, 700);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void showDialog(String text) {
        Dialog dialog = new AlertDialog.Builder(PowerActivity.this).setTitle("系统提示")
                .setMessage(text)// 设置内容
                .setPositiveButton("确定",// 设置确定按钮
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).create();// 创建
        // 显示对话框
        dialog.show();
    }

    private TextView getTitleTextView(String text) {
        final float scale = this. getResources().getDisplayMetrics().density;
        int dp10 = (int) (10 * scale + 0.5f);
        int dp12 = (int) (12 * scale + 0.5f);
        int dp25 = (int) (25 * scale + 0.5f);

        TextView title = new TextView(PowerActivity.this);
        LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp25);
        titleParams.weight = 1;
        titleParams.setMargins(dp10, dp10,0, 0);
        title.setLayoutParams(titleParams);
        title.setGravity(Gravity.CENTER|Gravity.LEFT);
        title.setTextColor(Color.parseColor("#4a4a4a"));
        title.setTextSize(dp10);
        title.setText(text);

        return title;
    }

    private Button getQuickSetup() {
        final float scale = this.getResources().getDisplayMetrics().density;
        int dp2 = (int) (2 * scale + 0.5f);
        int dp8 = (int) (8 * scale + 0.5f);
        int dp10 = (int) (10 * scale + 0.5f);
        int dp20 = (int) (20 * scale + 0.5f);

        Button button = new Button(PowerActivity.this);
        LinearLayout.LayoutParams buttonParams = new LinearLayout.LayoutParams((int) (280 * scale + 0.5f), LinearLayout.LayoutParams.WRAP_CONTENT);
        buttonParams.weight = 1;
        button.setLayoutParams(buttonParams);
        buttonParams.setMargins(0, dp2, dp10, 0);
        button.setTextColor(Color.parseColor("#ffffff"));
        button.setBackgroundResource(R.drawable.setting_power_btn);
        button.setMinHeight(dp10);
        button.setMinWidth(dp20);
        button.setTextSize(dp8);
        button.setText("快速设置");

        return button;
    }

    private TextView getComplete(String text) {
        final float scale = this. getResources().getDisplayMetrics().density;
        int dp10 = (int) (10 * scale + 0.5f);
        int dp8 = (int) (8 * scale + 0.5f);
        int dp25 = (int) (25 * scale + 0.5f);

        TextView content = new TextView(PowerActivity.this);
        LinearLayout.LayoutParams contentParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, dp25);
        contentParams.weight = 1;
        contentParams.setMargins(0, dp10, dp10, 0);
        content.setLayoutParams(contentParams);
        content.setGravity(Gravity.CENTER| Gravity.RIGHT);
        content.setTextColor(Color.parseColor("#4a4a4a"));
        content.setTextSize(dp8);
        content.setText(text);

        return content;
    }
}
